package com.edu.neusoft.student.controller;

import com.edu.neusoft.student.domain.Order;
import com.edu.neusoft.student.service.OrderService;
import com.edu.neusoft.student.util.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/orders")
@Api(tags = "Order Management API", description = "Operations related to order management")
@Validated
public class OrderController {

    @Autowired
    private OrderService orderService;

    // 根据ID获取订单
    @GetMapping("/{orderid}")
    @ApiOperation(value = "Get order by ID", notes = "Retrieve an order by its ID")
    public AjaxResult getOrderById(@PathVariable Integer orderid) {
        Order order = orderService.selectByPrimaryKey(orderid);
        if (order != null) {
            return AjaxResult.success("Order retrieved successfully", order);
        } else {
            return AjaxResult.error("Order not found");
        }
    }

    // 添加新订单
    @PostMapping
    @ApiOperation(value = "Add new order", notes = "Create a new order in the system")
    public AjaxResult addOrder(@Valid @RequestBody Order order) {
        int result = orderService.insert(order);
        if (result > 0) {
            return AjaxResult.success("Order added successfully");
        } else {
            return AjaxResult.error("Failed to add order");
        }
    }

    // 更新订单信息
    @PutMapping("/{orderid}")
    @ApiOperation(value = "Update an order", notes = "Update an existing order by its ID")
    public AjaxResult updateOrder(@PathVariable Integer orderid, @Valid @RequestBody Order order) {
        order.setOrderid(orderid); // 设置更新的ID
        int result = orderService.updateByPrimaryKey(order);
        if (result > 0) {
            return AjaxResult.success("Order updated successfully");
        } else {
            return AjaxResult.error("Failed to update order");
        }
    }

    // 删除订单
    @DeleteMapping("/{orderid}")
    @ApiOperation(value = "Delete an order", notes = "Delete an order by its ID")
    public AjaxResult deleteOrder(@PathVariable Integer orderid) {
        int result = orderService.deleteByPrimaryKey(orderid);
        if (result > 0) {
            return AjaxResult.success("Order deleted successfully");
        } else {
            return AjaxResult.error("Failed to delete order");
        }
    }
}
